package com.jcsz.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jcsz.common.to.mq.SeckillOrderTo;
import com.jcsz.common.utils.R;
import com.jcsz.common.vo.MemberRespVo;
import com.jcsz.gulimall.seckill.feign.CouponFeignService;
import com.jcsz.gulimall.seckill.feign.ProductFeignService;
import com.jcsz.gulimall.seckill.interceptor.LoginInterceptor;
import com.jcsz.gulimall.seckill.service.SeckillService;
import com.jcsz.gulimall.seckill.to.SeckillSkuRedisTo;
import com.jcsz.gulimall.seckill.vo.SeckillSessionVo;
import com.jcsz.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @className: SeckillServiceImpl
 * @author: 一把Po吉他
 * @date: 2022/11/17 22:47
 * @version: 1.0
 **/
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSION__CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode() == 200) {
            List<SeckillSessionVo> seckillSessionVos = r.get("info", new TypeReference<List<SeckillSessionVo>>() {
            });
            if (seckillSessionVos != null && seckillSessionVos.size() > 0) {
                //保存秒杀活动信息
                saveSessionInfos(seckillSessionVos);
                //保存秒杀商品信息
                saveSessionSkuInfo(seckillSessionVos);
            }

        }

    }


    /**
     * 缓存秒杀活动信息
     */
    private void saveSessionInfos(List<SeckillSessionVo> seckillSessionVos) {

        seckillSessionVos.stream().forEach((obj) -> {
            //获取当前活动的开始和结束时间的时间戳
            long startTime = obj.getStartTime().getTime();
            long endTime = obj.getEndTime().getTime();

            //存入到Redis中的key
            String key = SESSION__CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = obj.getSeckillSkuRelationEntities().stream().map((item) -> {
                    return obj.getId() + "_" + item.getSkuId().toString();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }

        });
    }

    private void saveSessionSkuInfo(List<SeckillSessionVo> seckillSessionVos) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
        seckillSessionVos.stream().forEach((obj) -> {
            obj.getSeckillSkuRelationEntities().stream().forEach((item) -> {
                String redisKey = item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString();
                Boolean hasKey = operations.hasKey(redisKey);
                if (!hasKey) {
                    //sku的秒杀信息
                    BeanUtils.copyProperties(item, seckillSkuRedisTo);
                    R r = productFeignService.getSkuInfo(item.getSkuId());
                    SkuInfoVo skuInfo = null;
                    if (r.getCode() == 200) {
                        skuInfo = r.get("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                    }
                    //设置当前商品的秒杀时间信息
                    seckillSkuRedisTo.setStartTime(obj.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(obj.getEndTime().getTime());
                    //设置当前秒杀商品基本信息
                    seckillSkuRedisTo.setSkuInfo(skuInfo);
                    //设置商品的随机码（防止恶意攻击）
                    String token = UUID.randomUUID().toString().replace("_", "");
                    seckillSkuRedisTo.setRandomCode(token);
                    String jsonString = JSON.toJSONString(seckillSkuRedisTo);
                    operations.put(redisKey, jsonString);

                    //如果当前这个场次的商品库存信息已经上架就不需要上架
                    //使用库存作为分布式Redisson信号量（限流）
                    // 使用库存作为分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(item.getSeckillCount());
                }

            });
        });
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前属于哪个秒杀场次
        long now = System.currentTimeMillis();
        Date date = new Date(now);
        System.out.println(date);
        //从Redis中查询到所有key以seckill:sessions开头的所有数据
        Set<String> keys = redisTemplate.keys(SESSION__CACHE_PREFIX + "*");
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            String[] s = next.replace(SESSION__CACHE_PREFIX, "").split("_");
            //获取存入Redis商品的开始时间
            long start = Long.parseLong(s[0]);
            Date date1 = new Date(start);
            System.out.println(date1);
            //获取存入Redis商品的结束时间
            long end = Long.parseLong(s[1]);
            //判断是否是当前秒杀场次
            if (now >= start && now <= end) {
                BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                List<String> range = redisTemplate.opsForList().range(next, -100, 100);
                String s1 = operations.get(range.get(0));
                System.out.println(s1);
                List<String> strings = operations.multiGet(range);
                if (strings.size() > 0 && strings != null) {
                    List<SeckillSkuRedisTo> collect = strings.stream().map((item) -> {
                        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                        // redisTo.setRandomCode(null);当前秒杀开始需要随机码
                        return seckillSkuRedisTo;

                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    //根据skuId查询商品是否参加秒杀活动
    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {
        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        Set<String> keys = operations.keys();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            String reg = "\\d_" + skuId;
            if (Pattern.matches(reg, next)) {
                String valueString = operations.get(next);
                SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(valueString, SeckillSkuRedisTo.class);
                Long now = System.currentTimeMillis();
                Long startTime = seckillSkuRedisTo.getStartTime();
                Long endTime = seckillSkuRedisTo.getEndTime();
                if (now >= startTime && now <= endTime) {
                    return seckillSkuRedisTo;
                } else {
                    seckillSkuRedisTo.setRandomCode(null);
                    return seckillSkuRedisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String code, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();

        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        String stringJson = operations.get(killId);
        if (stringJson != null) {
            SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(stringJson, SeckillSkuRedisTo.class);
            Long startTime = seckillSkuRedisTo.getStartTime();
            Long endTime = seckillSkuRedisTo.getEndTime();
            Long now = System.currentTimeMillis();
            //先验证时间
            if (now >= startTime && now <= endTime) {
                String randomCode = seckillSkuRedisTo.getRandomCode();
                String session_skuId = seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();
                //再验证防伪码
                if (code.equals(randomCode) && killId.equals(session_skuId)) {
                    //验证购物数量是否合理和库存量是否充足
                    Integer seckillLimit = seckillSkuRedisTo.getSeckillLimit();
                    //获取信号量
                    String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE + code);
                    Integer count = Integer.valueOf(seckillCount);
                    //判断信号量是否大于0,并且买的数量不能超过库存
                    if (count > 0 && num <= seckillLimit && count >= num) {
                        //设置自动过期(活动结束时间-当前时间)
                        Long ttl = endTime - now;
                        String redisKey = memberRespVo.getId() + "_" + seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();
                        Boolean flag = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (flag) {
                            try {
                                //占位成功说明从来没有买过,分布式锁(获取信号量-1)
                                RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + code);
                                //TODO 秒杀成功，快速下单
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                //保证Redis中还有商品库存
                                if (b) {
                                    //创建订单号和订单信息发送给MQ
                                    // 秒杀成功 快速下单 发送消息到 MQ 整个操作时间在 10ms 左右
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(timeId);
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                                    seckillOrderTo.setMemberId(memberRespVo.getId());
                                    seckillOrderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);

                                    long s2 = System.currentTimeMillis();
                                    log.info("耗时..." + (s2 - s1));
                                    return timeId;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    }


                }
            }


        }
        return null;
    }


}
